aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(app)/send/invoice/[id]/+page.server.ts
blob: 70b007a8a204a9de8b1d5b01d24234e3a6bef583 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import getRates from "$lib/rates";
import { auth, fd, get, post, types } from "$lib/utils";
import { error, fail, redirect } from "@sveltejs/kit";

export async function load({ cookies, depends, params: { id }, parent }) {
	depends("app:trust");
	const { subject, user } = await parent();
	const aid = cookies.get("aid") || user.id;
	const pin = cookies.get("pin");

	let invoice = await get(`/invoice/${id}`);

	const trust = await get("/trust", auth(cookies));
	const trusted = trust.includes(invoice.uid);
	if (trusted && (pin || !user.haspin)) {
		let p;
		try {
			if (!invoice.tip && invoice.user.prompt) {
				if (user.tip > 0) {
					invoice.tip = Math.round(invoice.amount * (user.tip / 100));
					invoice = await post(`/invoice/${id}`, { invoice }, auth(cookies));
				} else {
					throw new Error("tip");
				}
			}
			p = await post("/payments", { ...invoice, pin }, auth(cookies));
		} catch (e) {
			const { message } = e as Error;
			if (message === "tip") redirect(307, `/invoice/${id}/tip`);
			fail(400, { message });
		}
		if (p) redirect(307, `/sent/${p.id}`);
	}

	if (invoice.amount && invoice.prompt && invoice.tip === null)
		redirect(307, `/invoice/${id}/tip`);

	if (invoice.memoPrompt && invoice.memo === null)
		redirect(307, `/invoice/${id}/memo`);

	if (user && invoice.aid === aid)
		error(500, { message: "Cannot send to self" });
	else if (user && ![types.lightning, types.bolt12].includes(invoice.type))
		redirect(
			307,
			`/send/${invoice.type === types.ecash ? "ecash" : "bitcoin"}/${
				invoice.hash
			}`,
		);

	if (!user) redirect(307, `/invoice/${id}`);

	const rates = await getRates();
	const rate = rates[user.currency];
	const invoiceRate = rates[invoice.currency];

	const { balance } = await get(`/account/${aid}`, auth(cookies));
	return { balance, invoice, user, rate, invoiceRate, trusted };
}

export const actions = {
	default: async ({ cookies, params: { id }, request }) => {
		let p;
		try {
			const body = await fd(request);
			body.hash = id;

			p = await post("/payments", body, auth(cookies));
		} catch (e) {
			const { message } = e as Error;
			console.log("payment failed", id, e);
			error(500, { message });
		}

		redirect(307, `/sent/${p.id}`);
	},
};